<template>
  <div>
    <div class="table-operator">
      <a-button v-action:add type="primary" icon="check-circle" @click="validate" :loading="loading">保存</a-button>
      <a-button v-action:add icon="rollback" @click="handleGoBack">返回</a-button>
    </div>
    <a-card class="card" title="商家券基本信息">
      <a-form @submit="handleSubmit" :form="form" class="form">
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="归属商户">
              <a-tree-select :disabled="isDisabled"
                             :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                             placeholder='请选择'
                             allowClear
                             treeDefaultExpandAll
                             :treeData="treeData"
                             v-decorator="[ 'parentCode', {rules: [{ required: true, message: '请选择。。。' }]} ]"
              >
              <span style="color:#08c" slot="title" slot-scope="{key}">
                {{value}}
              </span>>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次名称">
              <a-input placeholder="批次名称" :disabled="isDisabled"
                       v-decorator="['stockName', {rules: [{ required: true, message: '必输', whitespace: true}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次类型">
              <a-select placeholder="批次类型" :disabled="isDisabled"
                        v-decorator="[ 'stockType', {rules: [{required: true, message: '必输'}, ],initialValue:'merNORMAL'} ]" >
                <a-select-option value="merNORMAL">固定面额满减券</a-select-option>
                <!--<a-select-option value="DISCOUNT">折扣券</a-select-option>
                <a-select-option value="EXCHANGE">换购券</a-select-option>-->
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次面额">
              <a-input placeholder="批次面额" addonAfter="元" :disabled="isDisabled"
                       v-decorator="['couponAmount', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="消费满多少元可用">
              <a-input placeholder="消费满多少元可用" addonAfter="元" :disabled="isDisabled"
                       v-decorator="['transactionMinimum', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="可用时间">
              <a-range-picker style="width: 100%" :disabled="isDisabled" v-decorator="[ 'validTime', rangeConfig]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次总预算">
              <a-input placeholder="批次总预算" addonAfter="元" :disabled="isDisabled"
                       v-decorator="['maxAmount', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="批次最大发放个数">
              <a-input placeholder="批次最大发放个数" addonAfter="个" :disabled="isDisabled"
                       v-decorator="['maxCoupons', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="用户最大可领个数">
              <a-input placeholder="用户最大可领个数" addonAfter="个" :disabled="isDisabled"
                       v-decorator="['maxCouponsPerUser', {rules: [{required: true, message: '必输'}]} ]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="是否过期自动退款">
              <a-radio-group buttonStyle="solid" v-decorator="[ 'isRefund', {rules: [{ required: true, message: '请选择' }], initialValue: false}]">
                <!--<a-radio-button :value="1">免费优惠券</a-radio-button>-->
                <a-radio-button :value="false">否</a-radio-button>
                <a-radio-button :value="true">是</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="类型">
              <a-radio-group buttonStyle="solid" v-decorator="[ 'type', {rules: [{ required: true, message: '请选择' }], initialValue: 2}]">
                <!--<a-radio-button :value="1">免费优惠券</a-radio-button>-->
                <a-radio-button :value="2">收费优惠券</a-radio-button>
                <a-radio-button :value="3">积分兑换</a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="金额">
              <a-input placeholder="金额" addonAfter="元/积分" v-decorator="[ 'amount', {rules: [{required: true, message: '必输'}] }]"/>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="排序">
              <a-input placeholder="排序" v-decorator="[ 'sortNo', {rules: [] }]"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="使用说明">
              <a-textarea placeholder="使用说明" v-decorator="['description', {rules: [{required: true, message: '必输'}]} ]" :rows="4"/>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="图片">
              <a-upload
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :action="baseUrl + '/sys/upload/uploadFile'"
                :beforeUpload="beforeUpload"
                @change="handleChange"
              >
                <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="300px"/>
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">Upload</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="form-row" :gutter="96">
          <a-col :lg="8" :md="12" :sm="24">
            <a-form-item label="每日限额(只针对购买生效)">
              <a-input placeholder="每日限额(只针对购买生效)" v-decorator="[ 'onedayQuota', {rules: [] }]"/>
            </a-form-item>
          </a-col>
        </a-row>

      </a-form>
    </a-card>

    <!--<footer-tool-bar
      :style="{ width: isSideMenu() && isDesktop() ? `calc(100% - ${sidebarOpened ? 256 : 80}px)` : '100%'}">
      <a-button style="margin-right: 8px" @click="handleGoBack()">返回</a-button>
      <a-button type="primary" @click="validate" :loading="loading">提交</a-button>
    </footer-tool-bar>-->
  </div>
</template>

<script>
  import moment from 'moment';
  import pick from 'lodash.pick'
  import FooterToolBar from '@/components/FooterToolbar'
  import { selectMerchantTree } from '@/api/shop/merchant'
  import { saveOrUpdate2 } from '@/api/shop/coupon'

  export default {
    components: {
      FooterToolBar
    },
    props: {
      record: {
        type: [Object, String],
        default: ''
      }
    },
    data () {
      return {
        id: null,
        loading: false,
        isDisabled: false,
        treeData:[],
        imageUrl: '',
        fileName: null,
        form: this.$form.createForm(this),
        baseUrl: process.env.VUE_APP_API_BASE_URL,
        rangeConfig: {
          rules: [{ type: 'array', required: true, message: '必选!' }],
        },
      }
    },
    mounted () {
      const params = {'isDisable': true}
      selectMerchantTree(params).then(res => {
        if (res.code === 200) {
          this.treeData = res.result
          this.$nextTick(() => {
            this.loadEditInfo(this.record)
          })
        }
      })
    },
    methods: {
      handleGoBack () {
        this.$emit('onGoBack')
      },
      handleSubmit (e) {
        e.preventDefault()
      },
      validate () {
        this.loading = true
        this.form.validateFields((err, values) => {
          if (!err) {
            values.id = this.id
            values.filename = this.filename
            if (values.type == 2) {
              values.amount = values.amount != undefined ? values.amount * 100 : undefined
            }
            values.couponAmount = values.couponAmount * 100
            values.transactionMinimum = values.transactionMinimum * 100
            values.maxAmount = values.maxAmount * 100
            values.availableBeginTime = values['validTime'][0].format('YYYY-MM-DD')
            values.availableEndTime = values['validTime'][1].format('YYYY-MM-DD')
            saveOrUpdate2(values).then((res) => {
              this.loading = false
              if (res.code === 200) {
                this.handleGoBack()
              }
            })
          } else {
            this.loading = false
          }
        })
      },
      loadEditInfo (record) {
        if (!record) {
          return
        }
        this.id = record.id
        this.isDisabled = true
        this.imageUrl = record.couponPicUrl
        let data = Object.assign({}, record)
        if (record.type ===2) {
          data.amount = data.amount * 0.01
        }
        let validTime = []
        validTime.push(moment(record.availableBeginTime))
        validTime.push(moment(record.availableEndTime))
        data.validTime = validTime
        data.couponAmount = data.couponAmount * 0.01
        data.transactionMinimum = data.transactionMinimum * 0.01
        data.maxAmount = data.maxAmount * 0.01
        const { form } = this
        const formData = pick(data, ['parentCode', 'stockName', 'stockType', 'couponAmount', 'transactionMinimum', 'validTime', 'maxAmount',
          'maxCoupons', 'maxCouponsPerUser', 'sortNo', 'type', 'amount', 'description', 'isRefund', 'onedayQuota'])
        form.setFieldsValue(formData)
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.imageUrl = info.file.response.fileUrl;
          this.filename = info.file.response.filename
          this.loading = false;
        }
      },
      beforeUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        // if (!isJPG) {
        //   this.$message.error('You can only upload JPG file!');
        // }
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error('Image must smaller than 2MB!');
        // }
        return true;
      },
    }
  }
</script>

<style lang="less" scoped>
  .card {
    margin-bottom: 24px;
  }

  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }

  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;

    i {
      margin-right: 4px;
    }
  }

  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;

    &:hover {
      background: #e6f7ff;
    }

    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }

    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0, 0, 0, .45);
      font-size: 12px;
    }
  }
</style>
